package com.chinalwb.are.demo;

import com.chinalwb.are.LogUtil;
import ohos.aafwk.ability.Ability;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.IBundleManager;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * DemoUtil
 *
 * @since 2021/06/22
 */
public class DemoUtil {
    /**
     * 存文本
     *
     * @param ability ability
     * @param html    html
     */
    public static void saveHtml(Ability ability, String html) {
        FileWriter fileWriter = null;
        try {
            if (ability.verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") !=
                    IBundleManager.PERMISSION_GRANTED) {
                ability.requestPermissionsFromUser(
                        new String[]{"ohos.permission.WRITE_USER_STORAGE"}, 1);
                return;
            }
            String filePath = ability.getExternalCacheDir() + File.separator + "ARE" + File.separator;
            File dir = new File(filePath);
            if (!dir.exists()) {
                boolean mkdir = dir.mkdir();
                LogUtil.loge("DemoUtil", "mkdir=" + mkdir);
            }
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_hh_mm_ss");
            String time = dateFormat.format(new Date());
            String fileName = time.concat(".html");

            File file = new File(filePath + fileName);
            if (!file.exists()) {
                boolean isCreated = file.createNewFile();
                if (!isCreated) {
                    new ToastDialog(ability).setText("Cannot create file at: " + filePath).show();
                    return;
                }
            }
            fileWriter = new FileWriter(file);
            fileWriter.write(html);
            new ToastDialog(ability).setText(fileName + " has been saved at " + filePath).show();
        } catch (IOException e) {
            e.printStackTrace();
            new ToastDialog(ability).setText("Run into error: " + e.getMessage()).show();
        } finally {
            try {
                if (fileWriter != null) {
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 状态栏
     *
     * @param ability ability
     */
    public static void initStatus(Ability ability) {
        try {
            int color = ability.getResourceManager().getElement(ResourceTable.String_status_bar_color).getColor();
            ability.getWindow().setStatusBarColor(color);
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
    }
}
